import React, { useState, useEffect } from 'react';
import { uReal, cline, ErrView, Wait, BaseDlg, NuiBt } from 'sui';
import { g_db } from 'db/state';
import { loc } from 'local';
import { Scan, Pcode} from '../sort/ctl/ctl';

const DlgFree = ({ open, setOpen, cur }) => {
    const [fin, setFin] = useState("scan");
    const [err, setErr] = useState("");
    const [wait, setWait] = useState(false);

    useEffect(() => {
        if (!open) {
            return;
        }

        setErr("");

        g_db.stop_scan();
    }, [open]);

    const hok = (sn) => {
        setWait(true);

        const herr = (e) => {
            setErr(e);
            setWait(false);
        };

        const cmd = {
            line: cline(),
            tp: cur,
            sn: sn,
        };

        if (cur === "away") {
            cmd["pack"] = true;
        }

        uReal(null, "pair/remove", cmd,
            r => {
                setWait(false);
                setOpen(false);
            },
            e => herr("解绑轴承出错"));
    };

    const getView = () => {
        if (fin === "scan") {
            return <Scan hcmd={hok} open={open} setOpen={setOpen} lok="解绑"/>;
        }

        return <Pcode hcmd={hok} open={open} setOpen={setOpen} lok="解绑"/>;
    };

    return (
        <BaseDlg open={open} title="解绑轴承">
            <div className="flex flex-col">
                <ErrView err={err}/>
                <div className="flex flex-row ml-4">
                    <NuiBt color={fin === "scan" ? "green": "blue"} hcmd={() => setFin("scan")}>{loc("base_62")}</NuiBt>
                    <NuiBt className="ml-4" color={fin === "scan" ? "blue": "green"} hcmd={() => setFin("pass")}>{loc("base_59")}</NuiBt>
                </div>
                {getView()}
                <Wait wait={wait}/>
            </div>
        </BaseDlg>
    );
};

export {DlgFree};
